package com.example.demo.leetcode100题;

import com.example.demo.StopWatchTemplate;
import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * @author：zzc
 * @date: 2022/9/4
 */
public class 二叉树的后序遍历 {

    // 左 右 中

    public static void main(String[] args) {

        System.out.println(StopWatchTemplate.doSupplier(() -> houxubianli2(new TreeNode())));
    }

    private static List<Integer> houxubianli2(TreeNode root) {

        List<Integer> res = new ArrayList<Integer>();
        Deque<TreeNode> stack = new LinkedList<TreeNode>();
        TreeNode prevAccess = null;
        while (root != null || !stack.isEmpty()) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            if (root.right == null || root.right == prevAccess) {
                res.add(root.val);
                prevAccess = root;
                root = null;
            } else {
                stack.push(root);
                root = root.right;
            }
        }

        return res;
    }

    private static List<Integer> houxubianli(TreeNode root) {

        ArrayList<Integer> objects = new ArrayList<>();

        assesNode(root, objects);

        return objects;

    }

    private static void assesNode(TreeNode root, ArrayList<Integer> objects) {
        if (root == null) {
            return;
        }

        assesNode(root.left, objects);
        assesNode(root.right, objects);
        objects.add(root.val);
    }

}
